package com.gxuwz.zhangjiahui.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.zhangjiahui.entity.Enclosure;
import com.gxuwz.zhangjiahui.entity.Project;
import com.gxuwz.zhangjiahui.service.IEnclosureService;
import com.gxuwz.zhangjiahui.service.IProjectService;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-06-20
 */
@Controller
@RequestMapping("/enclosure")
public class EnclosureController {

    @Autowired
    private IEnclosureService iEnclosureService;
    @Autowired
    private IProjectService iProjectService;


    /**
     * 查询全部信息
     * @param modelAndView
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @Pointcut
    @ResponseBody
    @RequestMapping(value = "/findEnclosure")
    public ModelAndView findEnclosure(ModelAndView modelAndView, Page page, Integer pageNumber, Enclosure Enclosure,
                                    @Param("enclosureId") String enclosureId, @Param("key") Integer key,
                                    HttpServletRequest request, HttpServletResponse response) {
        if(request.getSession().getAttribute("nowResult") != null){
            if (!request.getSession().getAttribute("nowResult").equals("now")) {
                request.getSession().setAttribute("result", "");
            }
            request.getSession().setAttribute("nowResult", "");
        }
        // 可以通过 wrapper 进行筛选!!!
        QueryWrapper<Enclosure> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("enclosure_id");
        // 进行模糊查询!!!
        if(enclosureId != null && enclosureId != ""){
            wrapper.like("enclosure_id", enclosureId);
            request.getSession().setAttribute("enclosureId", enclosureId);
        }else {
            request.getSession().setAttribute("enclosureId", "");
        }
        // 进行筛选
        Project project = new Project();
        if(key != null && key == 1){
            // 查询该学生的项目
            // 学号
            String stuNo = (String) request.getSession().getAttribute("studentNo");
            // 团队ID
            if(Integer.valueOf(String.valueOf(request.getSession().getAttribute("teamStuNo"))) == 1){ // 如果存在团队项目，且自己为队长
                project.setProjectId((String) request.getSession().getAttribute("studentNo"));
                project.setTeamId(String.valueOf(request.getSession().getAttribute("teamStuNo")));
                List<Project> projectList = iProjectService.findProjectByStuNoOrTeamId(project);
                if(projectList != null){
                    for(Project project1: projectList){
                        // and ( a or b )： 语法: wrapper.and(i -> i.eq().or().eq())
                        wrapper.eq("project_id", project1.getProjectId()).or();
                    }
                }
            }else { // 如果为单人项目
                project.setProjectId((String) request.getSession().getAttribute("studentNo"));
                List<Project> projectList = iProjectService.findProjectByStuNoOrTeamId(project);
                if(projectList != null){
                    for(Project project1: projectList){
                        // and ( a or b )： 语法: wrapper.and(i -> i.eq().or().eq())
                        wrapper.eq("project_id", project1.getProjectId()).or();
                    }
                }
            }
        }else if(key != null && key == 2){
            // 查询该指导老师指导的项目
            project.setProjectId((String) request.getSession().getAttribute("instructorNow"));
            List<Project> projectList = iProjectService.findProjectByStuNoOrTeamId(project);
            if(projectList != null){
                for(Project project1: projectList){
                    // and ( a or b )： 语法: wrapper.and(i -> i.eq().or().eq())
                    wrapper.eq("project_id", project1.getProjectId()).or();
                }
            }
        }
        // Current,页码 + Size,每页条数
        if(pageNumber == null){
            page.setCurrent(1);
        }else {
            page.setCurrent((long)pageNumber);
        }
        // 默认每页6行数据！
        page.setSize(6);
        // 调用分页查询方法！!
        IPage<Enclosure> enclosureIPage = iEnclosureService.selectEnclosurePage(page, wrapper);
        // 存放page，内有当前页数
        modelAndView.addObject("page", page);
        System.out.println("总条数"+enclosureIPage.getTotal());
        System.out.println("总页数"+enclosureIPage.getPages());
        // 存放总页数
        modelAndView.addObject("pages", (int)enclosureIPage.getPages());
        // 存放一个数组用来让foreach遍历
        int[] pagesList = new int[(int)enclosureIPage.getPages()];
        for(int i=0; i< (int)enclosureIPage.getPages(); i++){
            pagesList[i] = i+1;
        }
        modelAndView.addObject("pagesList", pagesList);
        modelAndView.addObject("numberPages", enclosureIPage.getTotal());
        List<Enclosure> enclosureList = enclosureIPage.getRecords();
        System.out.println("enclosureList = "+enclosureList);
        modelAndView.addObject("enclosureList", enclosureList);

        modelAndView.setViewName("enclosure/enclosure_list");
        return modelAndView;
    }



    /**
     * 添加/修改 信息
     * @param enclosure
     * @return
     */
    @RequestMapping(value = "/addEditEnclosure")
    public ModelAndView addEditEnclosure(Enclosure enclosure, HttpServletRequest request, ModelAndView modelAndView) {
        Enclosure enclosure1 = iEnclosureService.findEnclosureById(enclosure);
        System.out.println("enclosure = " + enclosure);
        System.out.println("enclosure1 = " + enclosure1);
        // 新增信息
        if(enclosure1 == null){
            System.out.println("进入新增");
            try {
                iEnclosureService.addEnclosure(enclosure);
                request.getSession().setAttribute("result", "addTrue");
                request.getSession().setAttribute("nowResult", "now");
            }catch (Exception e){
                request.getSession().setAttribute("result", "addFalse");
                request.getSession().setAttribute("nowResult", "now");
            }
        }
        // enclosure1
        if(enclosure1 != null){
            System.out.println("进入修改");
            try {
                iEnclosureService.updateEnclosureById(enclosure);
                request.getSession().setAttribute("result", "editTrue");
                request.getSession().setAttribute("nowResult", "now");
            }catch (Exception e){
                request.getSession().setAttribute("result", "editFalse");
                request.getSession().setAttribute("nowResult", "now");
            }
        }
        modelAndView.setViewName("redirect:/enclosure/findEnclosure");
        return modelAndView;
    }



    /**
     * 删除信息
     * @param enclosureId
     * @return
     */
    @GetMapping(value = "/deleteEnclosure")
    public ModelAndView deleteEnclosure(HttpServletRequest request, ModelAndView modelAndView,
                             @Param("enclosureId") String enclosureId) {
        Enclosure enclosure = new Enclosure();
        enclosure.setEnclosureId(enclosureId);
        try {
            iEnclosureService.deleteEnclosureById(enclosure);
            request.getSession().setAttribute("result", "deleteTrue");
            request.getSession().setAttribute("nowResult", "now");
        }catch (Exception e){

        }
        modelAndView.setViewName("redirect:/enclosure/findEnclosure");
        return modelAndView;
    }


    /**
     * 文件下载
     * @return
     */
    @RequestMapping(value = "/uploadEnclosure")
    public ModelAndView upload(HttpServletRequest request, ModelAndView modelAndView,
                               @RequestParam("enclosureId") String enclosureId) throws IOException {
        Enclosure enclosure = new Enclosure();
        enclosure.setEnclosureId(enclosureId);
        enclosure = iEnclosureService.findEnclosureById(enclosure);

        if(enclosure != null){
            // 通过路径查找指定目录下的文件
            String pathNow = System.getProperty("user.dir") + "\\src\\main\\resources\\static" + enclosure.getEnclosureUrl() + enclosure.getEnclosureName();
            String newName = enclosure.getEnclosureName();
            String filePath = "D:\\" + newName;
            // 拷贝
            copy(pathNow, filePath);

            request.getSession().setAttribute("result", "PDFTrue");
            request.getSession().setAttribute("nowResult", "now");
        }else {
            request.getSession().setAttribute("result", "PDFFalse");
            request.getSession().setAttribute("nowResult", "now");
        }
        modelAndView.setViewName("redirect:/enclosure/findEnclosure");
        return modelAndView;
    }

    private static void copy(String oldpath, String newpath) throws IOException {
        File oldpaths = new File(oldpath);
        File newpaths = new File(newpath);
        if (!newpaths.exists()) {
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        } else {
            newpaths.delete();
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        }
    }

}
